package se.sll.itintegration.catalogue.gui.service.view.users;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import se.sll.itintegration.catalogue.gui.entity.CareUnitEntity;
import se.sll.itintegration.catalogue.gui.entity.UserEntity;
import se.sll.itintegration.catalogue.gui.service.HsaCache;
import se.sll.service.catalogue.common.Translator;
import se.sll.service.catalogue.common.rest.model.user.CareUnitReference;
import se.sll.service.catalogue.common.rest.model.user.User;
import se.sll.service.catalogue.common.rest.response.HsaData;

/**
 * Translates from UserEntity to User.
 * Annotates CareUnitReferences with HSA names from HsaCache EJB.
 * 
 * @author Christer Palm, Nogui
 */
public class UserTranslator implements Translator<UserEntity, User> {
    private static final UserTranslator INSTANCE = new UserTranslator();
    private final HsaCache hsaCache;

    private UserTranslator() {
        try {
            InitialContext context = new InitialContext();
            //hsaCache = (HsaCache) context.lookup("java:global/gui-1.0-SNAPSHOT/HsaCache");
            hsaCache = (HsaCache) context.lookup("java:module/GUI-HSACache");
        } catch (NamingException ex) {
            throw new RuntimeException(ex);
        }
    }

    @Override
    public User translate(UserEntity from) {
        return translateTo(from, new User());
    }

    @Override
    public User translateTo(UserEntity from, User to) {
        to.setStatus(from.getStatus().name());
        to.setHsaId(from.getHsaID());
        to.setRole(from.getRole().name());
        to.setRealname(from.getRealname());
        to.setEmail(from.getEmail());
        to.setCreationTime(from.getCreationTime());
        to.setUpdatedTime(from.getUpdatedTime());
        to.setLastLogin(from.getLastLogin());

        Set<CareUnitEntity> careUnits = from.getCareUnits();
        List<CareUnitReference> userCareUnitsView = new ArrayList<>();
        for (CareUnitEntity careUnit : careUnits) {
            CareUnitReference viewCareUnit = new CareUnitReference();
            String hsaId = careUnit.getHsaID();
            viewCareUnit.setHsaId(hsaId);
            HsaData hsaData = hsaCache.getHsa(hsaId);
            if (hsaData != null) {
                viewCareUnit.setDisplayName(hsaData.getRelativeDistinguishedName());
            }
            userCareUnitsView.add(viewCareUnit);
        }
        to.setCareUnits(userCareUnitsView);
        return to;
    }

    public static UserTranslator getInstance() {
        return INSTANCE;
    }
}
